import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './modules/auth/auth.module';
import { TestModule } from './test/test.module';
import { User } from './modules/auth/entity/user.entity';
import { Menu } from './modules/menu/entity/menu.entity';
import { MenuModule } from './modules/menu/menu.module';
import { JwtAuthGuard } from './common/guard/jwt-auth.guard';
import { TransformInterceptor } from './common/interceptor/transform.interceptor';
import { HttpExceptionFilter } from './common/filters/httpException';
import {
  APP_GUARD,
  APP_INTERCEPTOR,
  Reflector,
  APP_FILTER,
} from '@nestjs/core';

@Module({
  imports: [
    // 配置环境变量
    ConfigModule.forRoot({
      isGlobal: true, // 全局可用
      envFilePath: ['.env', `.env.${process.env.NODE_ENV}`], // 加载.env和对应的环境文件
      cache: true, // 缓存环境变量以提高性能
    }),

    // 配置数据库连接，使用ConfigService来获取环境变量
    TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: 'mysql',
        host: configService.get('DB_HOST', 'localhost'),
        port: configService.get<number>('DB_PORT', 3306),
        username: configService.get('DB_USERNAME', 'root'),
        password: configService.get('DB_PASSWORD', 'password'),
        database: configService.get('DB_DATABASE', 'vite_vue_template'),
        entities: [User, Menu],
        synchronize: configService.get<boolean>('typeorm_synchronize', true),
        logging: configService.get<boolean>('ENABLE_LOGGING', true),
      }),
    }),

    AuthModule,
    TestModule,
    MenuModule,
  ],
  controllers: [AppController],
  providers: [
    AppService,
    // 全局注册JWT守卫
    {
      provide: APP_GUARD,
      useClass: JwtAuthGuard,
    },
    // 全局注册响应拦截器
    {
      provide: APP_INTERCEPTOR,
      useFactory: (reflector: Reflector) => new TransformInterceptor(reflector),
      inject: [Reflector],
    },
    // 全局注册异常过滤器
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter,
    },
  ],
})
export class AppModule {}
